package com.zzzzzz.plugins.shiro;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zzzzzz.sys.role.menu.RoleMenuDao;
import com.zzzzzz.sys.user.User;
import com.zzzzzz.sys.user.UserDao;

public class ShiroDbRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
	
	@Resource
	private UserDao userDao;
	@Resource
	private PasswordMatcher passwordMatcher;
	@Resource
	private PasswordService passwordService;
	@Resource
	private RoleMenuDao roleMenuDao;
	
	@PostConstruct
	public void initCredentialsMatcher() {
		setName("shiroDbRealm");
		passwordMatcher.setPasswordService(passwordService);
		setCredentialsMatcher(passwordMatcher);
	}
	
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		try{
			User user = userDao.findByAccount(token.getUsername());
			return new SimpleAuthenticationInfo(new I(user), user.getPassword(), getName());
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    		I i = (I) principalCollection.getPrimaryPrincipal();
		Long userId = i.getId();
		if(userId == null){
			return null;
		}
		// 添加角色及权限信息
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		try {
			List<Map<String, Object>> list = roleMenuDao.findListForPemisi(userId, i.getPlatformId());
			for (Map<String, Object> map : list){
				Object pemisiObj = map.get("pemisi");
				if (pemisiObj!=null){
					simpleAuthorizationInfo.addStringPermission(pemisiObj.toString());
				}
			}
		} catch (Exception e) {
			logger.warn("doGetAuthorizationInfo", e);
		}
		
		return simpleAuthorizationInfo;
    }
}
